package com.eascs.admin.o2o.internal.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.service.BaseSevice;
import com.eascs.admin.common.vo.ModelResult;
import com.eascs.admin.o2o.finance.entity.O2oFinanceFlowEntity;
import com.eascs.admin.o2o.finance.service.O2oFinanceFlowService;
import com.eascs.admin.o2o.internal.controller.PayMentController;
import com.eascs.admin.o2o.internal.dao.AuditCommentsDao;
import com.eascs.admin.o2o.internal.dao.LoanapplyExpandDao;
/**
 * 贷款管理
 * @author 
 *
 */
import com.eascs.admin.o2o.internal.dao.PayMentDao;
import com.eascs.admin.o2o.internal.entity.AuditComments;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.form.LoanapplyForm;
import com.eascs.admin.o2o.internal.form.PayMentSearchForm;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.dao.O2oLoanapplyDao;
import com.eascs.admin.o2o.loan.entity.O2oLoanBkInfo;
import com.eascs.admin.o2o.loan.entity.O2oLoanGsInfo;
import com.eascs.admin.o2o.loan.entity.O2oLoanGsMainproductInfo;
import com.eascs.admin.o2o.loan.entity.O2oLoanScInfo;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.form.PayMentForm;
import com.eascs.admin.o2o.loan.service.O2oLoanBkService;
import com.eascs.admin.o2o.loan.service.O2oLoanBkpService;
import com.eascs.admin.o2o.loan.service.O2oLoanBksyService;
import com.eascs.admin.o2o.loan.service.O2oLoanGsMainProductService;
import com.eascs.admin.o2o.loan.service.O2oLoanGsService;
import com.eascs.admin.o2o.loan.service.O2oLoanScService;
import com.eascs.admin.o2o.loan.service.O2oLoanScTopTenCService;
import com.eascs.admin.o2o.loan.service.O2oLoanScTopTenSService;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loan.utils.BankRate;
import com.eascs.admin.recordlog.constant.O2oLogType;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.nsEditDetail.entity.AssetsTotInfoEntity;
import com.eascs.crm.nsEditDetail.entity.CustomerShopInfoEntity;
import com.eascs.crm.nsEditDetail.entity.ManagementInfoEntity;
import com.eascs.crm.nsEditDetail.entity.O2oMainShopInfoEntity;
import com.eascs.crm.nsEditDetail.service.AssetsTotInfoService;
import com.eascs.crm.nsEditDetail.service.ContactsInfoService;
import com.eascs.crm.nsEditDetail.service.CustomerAssetInfoService;
import com.eascs.crm.nsEditDetail.service.CustomerShopInfoService;
import com.eascs.crm.nsEditDetail.service.IMainShopInfoService;
import com.eascs.crm.nsEditDetail.service.ManagementInfoService;
import com.eascs.gaczcontract.entity.CustomerBasicInfo;
import com.eascs.web.sso.UserHolder;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class PayMentService extends BaseSevice {
	private static final Logger logger = LoggerFactory.getLogger(PayMentController.class);
	@Autowired
	private PayMentDao payMentDao;

	@Autowired
	private O2oLoanapplyDao loanDao;

	@Autowired
	private AuditCommentsDao auditCommentsDao;

	@Autowired
	private LoanapplyExpandDao loanapplyExpandDao;

	@Autowired
	private BaseUserUtil userUtils;

	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	
	@Autowired
	private  O2oFinanceFlowService financeFlowService;
	
	@Autowired
	CustomerAssetInfoService customerAssetInfoService;

	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	
	@Autowired
	CustomerShopInfoService customerShopInfoService;
	
	@Autowired
	private LoanapplyExpandService loanapplyExpandService;
	@Autowired
	ContactsInfoService contactsInfoService;
	
	@Inject
	AssetsTotInfoService assetsInfoService;
	
	@Reference
	IMainShopInfoService mainShopInfoService;
	
	@Autowired
	private ManagementInfoService managementInfoService;
	
	@Autowired
	O2oLoanBkService o2oLoanBkService;
	
	@Autowired
	O2oLoanBksyService o2oLoanBksyService;
	
	@Autowired
	O2oLoanBkpService o2oLoanBkpService;
	
	@Autowired
	O2oLoanGsMainProductService productService;
	
	@Autowired
	O2oLoanScTopTenSService tenSService;
	
	@Autowired
	O2oLoanScTopTenCService cService;
	
	public ModelResult<Boolean> sumformCheck(PayMentForm payform) {
		ModelResult<Boolean> modelResult = new ModelResult<Boolean>().withModel(Boolean.TRUE);//默认是成功
		O2oLoanapplyEntity loan = null;
		
		//校验借款人和配偶、担保人联系电话是否相同
		Boolean flag = o2oLoanUserService.getCheckUserPhone(payform.getLoanapplyNo());
		if(flag){
			return modelResult.withModel(false).withError("NSCHECK_100_1", "借款人和配偶、担保人联系电话有重复，请进行检查修改!");
		}
		if(payform.getLoanapplyNo()!=null){
			 loan = o2oLoanapplyService.findById(payform.getLoanapplyNo());
			if(loan==null){
				return modelResult.withModel(false).withError("NSCHECK_000_1", "贷款单号不存在请检查！");
			}
			
		}else{
			
			return modelResult.withModel(false).withError("NSCHECK_000", "未传贷款单id请检查！");
		}
		
		if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)&&StatusContexts.OPERATION_MODEL_PTDB.equals(loan.getOperationModel())){
			O2oFinanceFlowEntity entity = financeFlowService.getByLoanApplyno(payform.getLoanapplyNo());
			if (entity == null || entity.getFlowStatus().equals(StatusContexts.O2O_BANK_NEW) || entity.getFlowStatus().equals(StatusContexts.O2O_BANK_RUN)) {
				
				modelResult.setModel(false);
				modelResult.withError("NSCHECK_001", "财务审核流程未结束，不能发起内审");
				return modelResult;
			}
		}
		if (!StatusContexts.O2O_ZX_END.equals(loan.getWfType())) {
			modelResult.setModel(false);
			modelResult.withError("NSCHECK_002", "征信流程未完成");
			return modelResult;
		}
		//检查贷款的基本信息
		String  checkLoanApply= checkLoanApply(loan);  
		if(!checkLoanApply.endsWith(StatusContexts.SUCCESS)){
			modelResult.setModel(false);
			modelResult.withError("NSCHECK_003", checkLoanApply);
			return modelResult;
		}
		O2oLoanUserEntity  baseUserEntity=o2oLoanUserService.findById(loan.getLoanId(), loan.getLoanapplyNo());
		String  checkNS= checkNS(baseUserEntity);  //检查主申请人基本信息
		if(!checkNS.endsWith(StatusContexts.SUCCESS)){
			modelResult.setModel(false);
			modelResult.withError("NSCHECK_004", checkNS);
			return modelResult;
		}
		//1.查询配偶有没存在 2.不存在 ：检测是否有新增配偶关系
		O2oLoanUserEntity  userEntity=o2oLoanUserService.findSpouseId(loan.getLoanId(), loan.getLoanapplyNo());
		if(userEntity!=null){
			//内审检查配偶信息
			String  checkSpouseNS= checkSpouseNS(userEntity); //检查
			if(!checkSpouseNS.endsWith(StatusContexts.SUCCESS)){
				modelResult.setModel(false);
				modelResult.withError("NSCHECK_005", checkSpouseNS);
				return modelResult;
			}
		}
		//检查紧急联系人
		int k = contactsInfoService.getByLoanNoNum(loan.getLoanapplyNo());
		if (k < 2) {
			
			return modelResult.withModel(false).withError("NSCHECK_008", "紧急联系人至少要2个，请编辑借款人信息");
		}
		
	/*	//资产信息校验-loan-11986 提交内审校验-1、在现在的基础上去掉紧急联系人校验、增加【客户资产信息】模块中的车产价值、放产净价值字段非空校验，（与鲁俊沟通确认）
		CustomerAssetInfo customerAssetInfo = customerAssetInfoService.queryById(loan.getLoanapplyNo());
		if (customerAssetInfo == null) {
			
			return modelResult.withModel(false).withError("NSCHECK_006", "客户资产信息未完善,请完善资产信息");
		} else {
			if(StringUtil.isBlank(customerAssetInfo.getHouseValue())){
				//return BaseRestResult.warn("客户资产信息未完善,请完善资产信息");
				return modelResult.withModel(false).withError("NSCHECK_006", "客户资产信息未完善,请完善资产信息");
			}
			if(StringUtil.isBlank(customerAssetInfo.getCarNetValue())){
				//return BaseRestResult.warn("客户资产信息未完善,请完善资产信息");
				return modelResult.withModel(false).withError("NSCHECK_006", "客户资产信息未完善,请完善资产信息");
			}
		}*/
		
		List<CustomerShopInfoEntity> shopInfoEntitys = customerShopInfoService.list(loan.getLoanapplyNo());
		if (shopInfoEntitys == null || shopInfoEntitys.size() <= 0) {
			return modelResult.withModel(false).withError("NSCHECK_007", "客户门店信息未完善,请新增门店信息");
		} /*else if (shopInfoEntitys.size() > 0) {
			List<String> strList = new ArrayList<String>();
			for (int i = 0; i < shopInfoEntitys.size(); i++) {
				strList.add(shopInfoEntitys.get(i).getShoptype());
			}
			if (!strList.contains("MAN")) {
				return modelResult.withModel(false).withError("NSCHECK_007_1", "门店中必须包含主门店,请新增门店信息");
			}
			for (int i = 0; i < shopInfoEntitys.size(); i++) {
				boolean shopName = StringUtil.isEmpty(shopInfoEntitys.get(i).getShopname());
				boolean shopType = StringUtil.isEmpty(shopInfoEntitys.get(i).getShoptype());
				boolean stupdate = StringUtil.isEmpty(shopInfoEntitys.get(i).getStupdate());
				boolean eacooperationdate = StringUtil.isEmpty(shopInfoEntitys.get(i).getEacooperationdate());
				boolean vocation = StringUtil.isEmpty(shopInfoEntitys.get(i).getVocation());
				boolean telephone = StringUtil.isEmpty(shopInfoEntitys.get(i).getTelephone());
				boolean officeprovince = StringUtil.isEmpty(shopInfoEntitys.get(i).getOfficeprovince());
				boolean officecity = StringUtil.isEmpty(shopInfoEntitys.get(i).getOfficecity());
				boolean gsQureyAbnermal = StringUtil.isEmpty(shopInfoEntitys.get(i).getGsQureyAbnermal());
				boolean employeeNum = StringUtil.isEmpty(shopInfoEntitys.get(i).getEmployeeNum());
				boolean grossProfitRate = StringUtil.isEmpty(shopInfoEntitys.get(i).getGrossProfitRate());
				boolean annualNetProfit = StringUtil.isEmpty(shopInfoEntitys.get(i).getAnnualNetProfit());
				//check 营业执照名称和营业执照地址
				if(("MAN").equals(shopInfoEntitys.get(i).getShoptype())){
					if(StringUtil.isEmpty(shopInfoEntitys.get(i).getLicenceName())){
						return modelResult.withModel(false).withError("NSCHECK_008_1", "请先完善主门店营业执照名称");
					}
					if(StringUtil.isEmpty(shopInfoEntitys.get(i).getLicenceAddress())){
						return modelResult.withModel(false).withError("NSCHECK_008_2", "请先完善主门店营业执照地址");
					}
					if(StringUtil.isEmpty(shopInfoEntitys.get(i).getEacooperationdate())){
						return modelResult.withModel(false).withError("NSCHECK_008_3", "主门店与怡亚通（含前身）合作开始时间不能为空");
					}
					if(shopInfoEntitys.get(i).getEapurchaseamount().compareTo(BigDecimal.ZERO)==0){
						return modelResult.withModel(false).withError("NSCHECK_008_4", "主门店向怡亚通月均采购额(以近6个月金额为标准)(元)不能为空");
					}
				}
				if (shopName || shopType || stupdate || eacooperationdate || vocation || telephone || officecity || officeprovince || gsQureyAbnermal || employeeNum || grossProfitRate || annualNetProfit)
					return modelResult.withModel(false).withError("NSCHECK_008", "客户门店信息未完善,请完善信息");
					//return BaseRestResult.warn("客户门店信息未完善,请完善信息");
			}
		}*/
		
		//检查信贷经理是否保存表单
		String  checkNsBd= checkNsBd(loan);  
		if(!checkNsBd.endsWith(StatusContexts.SUCCESS)){
			return modelResult.withModel(false).withError("NSCHECK_009", checkNsBd);
		}
		//检查信贷经理是否保存表单(蔬果贷商超贷)
		String  checkNsSG= checkNsSG(loan);  
		if(!checkNsSG.endsWith(StatusContexts.SUCCESS)){
			return modelResult.withModel(false).withError("NSCHECK_010", checkNsSG);
		}
		
		//新增加的表单check(新增内审) -------------------------------------------------------------
		//夫妻双方资产负债情况总览
		//tot_assets_show
		AssetsTotInfoEntity  vo = assetsInfoService.findAssetsTotInfoByLoanapplyId(loan.getLoanapplyNo());
		if(vo==null){
			return modelResult.withModel(false).withError("NSCHECK_011", "请先保存夫妻双方资产负债情况");
		}
		
		//经营主体信息 /mainShopInfoView
		O2oMainShopInfoEntity info = mainShopInfoService.getByLoanNo(loan.getLoanapplyNo());
		if(info==null){
			return modelResult.withModel(false).withError("NSCHECK_012", "请先保存经营主体信息");
		}
		
		//  经营状况  /managementInfo
		
		ManagementInfoEntity managementInfo = managementInfoService.getByLoanNo(loan.getLoanapplyNo());
		
		if(managementInfo==null){
			return modelResult.withModel(false).withError("NSCHECK_013", "请先保存经营状况信息");
		}
		
		// 不同类型贷款   经营补充信息 check 
		// loanType=='SG' /rmongo/gs_info_lno
		modelResult = checkJYBCXX(loan);
		
			return modelResult;
		}
	
	
	/**
	 * 分页查询贷款列表
	 * 
	 * @param payMentSearchForm
	 * @return
	 */
	public PageResult<Object[]> findByPage(PayMentSearchForm payMentSearchForm) {
		return payMentDao.findByPage(payMentSearchForm);
	}

	public PageResult<Object[]> findByPageExport(PayMentSearchForm payMentSearchForm) {
		return payMentDao.findByPageExport(payMentSearchForm);
	}
	
	/**
	 * 分期贷 内审表单_编辑内审
	 * 
	 * @param loanapplyForm
	 * @param user
	 * @param loanapply
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public void fQloan_ns(LoanapplyForm loanapplyForm, O2oLoanapplyEntity loanapply) {
		// 修改主表
		loanDao.updateLoanapply_ns(loanapplyForm, userUtils);
		// 记录到操作日志表
		ObjectMapper mapper = new ObjectMapper();
		try {
			o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_ND,
					mapper.writeValueAsString(loanapply), mapper.writeValueAsString(loanapply));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 收取保证金与管理费
		// 1.管理费=(贷款金额*年化费率)/12*贷款月数
		// 2.风险补偿金=(贷款金额*年化费率)/12*贷款月数
		// 3.保证金=贷款金额*费率
		LoanapplyExpand loanapplyExpand = loanapplyExpandDao.queryLoanapplyNo(loanapplyForm.getLoanapplyNo());
		BigDecimal year = new BigDecimal(12);
		// 管理费=(贷款金额*年化费率)/12*贷款月数
		BigDecimal loanTerm = new BigDecimal(loanapplyForm.getLoanTerm());
		// 分期贷管理费按实际月份收取
		BigDecimal manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate())).multiply(loanTerm).divide(year, 2, BigDecimal.ROUND_HALF_UP);
		if (loanapplyExpand == null) {
			LoanapplyExpand expand = new LoanapplyExpand();
			expand.setPaymentType(loanapplyForm.getPaymentType());
			expand.setBankLoanName(loanapplyForm.getBankLoanName());
			expand.setGeneralRate(loanapplyForm.getGeneralRate());
			expand.setBillStatus(StatusContexts.BZJ_STATUS_NEW);
			expand.setBillCode(loanapply.getBillCode());
			expand.setRisk(loanapplyForm.getRisk());
			expand.setUpdator(userUtils.getUpdateOr());
			expand.setCreator(userUtils.getCreateOr());
			expand.setCreat_time(new Date());
			expand.setUpdateTime(new Date());
			expand.setDelFlag(StatusContexts.O2O_NO);
			expand.setRemark(loanapplyForm.getRemark());
			expand.setLoanapply_no(loanapplyForm.getLoanapplyNo());
			// 保证金=贷款金额*费率
			expand.setRecDeposite((loanapplyForm.getEaMount()).multiply((loanapplyForm.getDepositrate())));
			expand.setReceiveDeposit((loanapplyForm.getEaMount()).multiply((loanapplyForm.getDepositrate())));
			//分期贷管理费按实际月份收取
			expand.setRecManger(manger);
			expand.setDepositrate(loanapplyForm.getDepositrate());
			expand.setManagefeerate(loanapplyForm.getManagefeerate());
			expand.setRecRisk(new BigDecimal(0));
			expand.setRisk(new BigDecimal(0));
			loanapplyExpandDao.insert(expand);
		} else {
			BigDecimal recRisk = new BigDecimal(0);
			loanapplyForm.setRisk(new BigDecimal(0));
			loanapplyExpandDao.updateLoanapplyExpand(manger, loanapply, loanapplyForm, recRisk, loanapplyExpand);
		}
		// 内审审批 历史记录
		AuditComments auditComments = new AuditComments();
		auditComments.setCreateDate(new Date());
		auditComments.setEmpLoyeNo(userUtils.getUser().getNo());
		auditComments.setRisk(loanapplyForm.getRisk());
		auditComments.setEmpLoyeName(userUtils.getUser().getCname());
		auditComments.setLoanapplyNo(loanapplyForm.getLoanapplyNo());
		auditComments.setLoanrate(loanapplyForm.getLoanrate());
		auditComments.setLoanterm(loanapplyForm.getLoanTerm());
		auditComments.setDepositrate(loanapplyForm.getDepositrate());
		auditComments.setRemark(loanapplyForm.getRemark());
		auditComments.setManagefeerate(loanapplyForm.getManagefeerate());
		auditComments.setCustomersalesamount(loanapply.getCustomerSalesamount());
		auditComments.setEacooperationdate(loanapply.getEaCooperationDate());
		auditComments.setEapurchaseamount(loanapply.getEaPurchaseamount());
		auditComments.setRepaymentway(loanapplyForm.getRepayMentway());
		auditComments.setBankLoanName(loanapplyForm.getBankLoanName());
		auditComments.setPaymentType(loanapplyForm.getPaymentType());
		auditComments.setGeneralRate(loanapplyForm.getGeneralRate());
		auditComments.setEaMount(loanapplyForm.getEaMount());
		auditCommentsDao.insert(auditComments);
	}
	
	/**
	 * 分期贷 内审表单
	 * 
	 * @param loanapplyForm
	 * @param user
	 * @param loanapply
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public void fQloan(LoanapplyForm loanapplyForm, O2oLoanapplyEntity loanapply) {
		// 修改主表
		loanDao.updateLoanapply(loanapplyForm, userUtils);
		// 记录到操作日志表
		ObjectMapper mapper = new ObjectMapper();
		try {
			o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_ND,
					mapper.writeValueAsString(loanapply), mapper.writeValueAsString(loanapply));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 收取保证金与管理费
		// 1.管理费=(贷款金额*年化费率)/12*贷款月数
		// 2.风险补偿金=(贷款金额*年化费率)/12*贷款月数
		// 3.保证金=贷款金额*费率
		LoanapplyExpand loanapplyExpand = loanapplyExpandDao.queryLoanapplyNo(loanapplyForm.getLoanapplyNo());
		BigDecimal year = new BigDecimal(12);
		// 管理费=(贷款金额*年化费率)/12*贷款月数
		BigDecimal loanTerm = new BigDecimal(loanapplyForm.getLoanTerm());
		// 分期贷管理费按实际月份收取
		BigDecimal manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate())).multiply(loanTerm).divide(year, 2, BigDecimal.ROUND_HALF_UP);
		if (loanapplyExpand == null) {
			LoanapplyExpand expand = new LoanapplyExpand();
			expand.setPaymentType(loanapplyForm.getPaymentType());
			expand.setBankLoanName(loanapplyForm.getBankLoanName());
			expand.setGeneralRate(loanapplyForm.getGeneralRate());
			expand.setBillStatus(StatusContexts.BZJ_STATUS_NEW);
			expand.setBillCode(loanapply.getBillCode());
			expand.setRisk(loanapplyForm.getRisk());
			expand.setUpdator(userUtils.getUpdateOr());
			expand.setCreator(userUtils.getCreateOr());
			expand.setCreat_time(new Date());
			expand.setUpdateTime(new Date());
			expand.setDelFlag(StatusContexts.O2O_NO);
			expand.setRemark(loanapplyForm.getRemark());
			expand.setLoanapply_no(loanapplyForm.getLoanapplyNo());
			// 保证金=贷款金额*费率
			expand.setRecDeposite((loanapplyForm.getEaMount()).multiply((loanapplyForm.getDepositrate())));
			expand.setReceiveDeposit((loanapplyForm.getEaMount()).multiply((loanapplyForm.getDepositrate())));
			//分期贷管理费按实际月份收取
			expand.setRecManger(manger);
			expand.setDepositrate(loanapplyForm.getDepositrate());
			expand.setManagefeerate(loanapplyForm.getManagefeerate());
			expand.setRecRisk(new BigDecimal(0));
			expand.setRisk(new BigDecimal(0));
			loanapplyExpandDao.insert(expand);
		} else {
			BigDecimal recRisk = new BigDecimal(0);
			loanapplyForm.setRisk(new BigDecimal(0));
			loanapplyExpandDao.updateLoanapplyExpand(manger, loanapply, loanapplyForm, recRisk, loanapplyExpand);
		}
		// 内审审批 历史记录
		AuditComments auditComments = new AuditComments();
		auditComments.setCreateDate(new Date());
		auditComments.setEmpLoyeNo(userUtils.getUser().getNo());
		auditComments.setRisk(loanapplyForm.getRisk());
		auditComments.setEmpLoyeName(userUtils.getUser().getCname());
		auditComments.setLoanapplyNo(loanapplyForm.getLoanapplyNo());
		auditComments.setLoanrate(loanapplyForm.getLoanrate());
		auditComments.setLoanterm(loanapplyForm.getLoanTerm());
		auditComments.setDepositrate(loanapplyForm.getDepositrate());
		auditComments.setRemark(loanapplyForm.getRemark());
		auditComments.setManagefeerate(loanapplyForm.getManagefeerate());
		auditComments.setCustomersalesamount(loanapply.getCustomerSalesamount());
		auditComments.setEacooperationdate(loanapply.getEaCooperationDate());
		auditComments.setEapurchaseamount(loanapply.getEaPurchaseamount());
		auditComments.setRepaymentway(loanapplyForm.getRepayMentway());
		auditComments.setBankLoanName(loanapplyForm.getBankLoanName());
		auditComments.setPaymentType(loanapplyForm.getPaymentType());
		auditComments.setGeneralRate(loanapplyForm.getGeneralRate());
		auditComments.setEaMount(loanapplyForm.getEaMount());
		auditCommentsDao.insert(auditComments);
	}

	/**
	 * 接力贷 内审表单_编辑内审
	 * 
	 * @param loanapplyForm
	 * @param user
	 * @param loanapply
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public void eAloan_ns(LoanapplyForm loanapplyForm, O2oLoanapplyEntity loanapply) {
		// 修改主表
		loanDao.updateLoanapply_ns(loanapplyForm, userUtils);
		// 记录到操作日志表
		ObjectMapper mapper = new ObjectMapper();
		try {
			o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_ND,
					mapper.writeValueAsString(loanapply), mapper.writeValueAsString(loanapply));
		} catch (Exception e) {
			e.printStackTrace();
		}
		LoanapplyExpand loanapplyExpand = loanapplyExpandDao.queryLoanapplyNo(loanapplyForm.getLoanapplyNo());
		BigDecimal year = new BigDecimal(12);
		// 管理费=(贷款金额*年化费率)/12*贷款月数
		BigDecimal manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate())).divide(year, 2, BigDecimal.ROUND_HALF_UP);
		if (loanapplyExpand == null) {
			LoanapplyExpand expand = new LoanapplyExpand();
			expand.setPaymentType(loanapplyForm.getPaymentType());
			expand.setBankLoanName(loanapplyForm.getBankLoanName());
			expand.setGeneralRate(loanapplyForm.getGeneralRate());
			expand.setBillStatus(StatusContexts.BZJ_STATUS_NEW);
			expand.setBillCode(loanapply.getBillCode());
			expand.setRisk(loanapplyForm.getRisk());
			expand.setUpdator(userUtils.getUpdateOr());
			expand.setCreator(userUtils.getCreateOr());
			expand.setCreat_time(new Date());
			expand.setUpdateTime(new Date());
			expand.setDelFlag(StatusContexts.O2O_NO);
			expand.setRemark(loanapplyForm.getRemark());
			expand.setLoanapply_no(loanapplyForm.getLoanapplyNo());
			
			expand.setRecManger(manger);
			expand.setDepositrate(loanapplyForm.getDepositrate());
			expand.setManagefeerate(loanapplyForm.getManagefeerate());
			expand.setRecRisk(new BigDecimal(0));
			expand.setRecDeposite(new BigDecimal(0));
			expand.setReceiveDeposit(new BigDecimal(0));;
			expand.setRisk(loanapplyForm.getRisk());
			loanapplyExpandDao.insert(expand);
		} else {
			BigDecimal recRisk = new BigDecimal(0);
			loanapplyForm.setRisk(new BigDecimal(0));
			loanapplyExpandDao.updateLoanapplyExpand(manger, loanapply, loanapplyForm, recRisk, loanapplyExpand);
		}
		// 内审审批 历史记录
		AuditComments auditComments = new AuditComments();
		auditComments.setCreateDate(new Date());
		auditComments.setEmpLoyeNo(userUtils.getUser().getNo());
		auditComments.setRisk(loanapplyForm.getRisk());
		auditComments.setEmpLoyeName(userUtils.getUser().getCname());
		auditComments.setLoanapplyNo(loanapplyForm.getLoanapplyNo());
		auditComments.setLoanrate(loanapplyForm.getLoanrate());
		auditComments.setLoanterm(loanapplyForm.getLoanTerm());
		auditComments.setDepositrate(loanapplyForm.getDepositrate());
		auditComments.setRemark(loanapplyForm.getRemark());
		auditComments.setManagefeerate(loanapplyForm.getManagefeerate());
		auditComments.setCustomersalesamount(loanapply.getCustomerSalesamount());
		auditComments.setEacooperationdate(loanapply.getEaCooperationDate());
		auditComments.setEapurchaseamount(loanapply.getEaPurchaseamount());
		auditComments.setRepaymentway(loanapplyForm.getRepayMentway());
		auditComments.setBankLoanName(loanapplyForm.getBankLoanName());
		auditComments.setPaymentType(loanapplyForm.getPaymentType());
		auditComments.setGeneralRate(loanapplyForm.getGeneralRate());
		auditComments.setEaMount(loanapplyForm.getEaMount());
		auditCommentsDao.insert(auditComments);
	}
	
	/**
	 * 接力贷 内审表单
	 * 
	 * @param loanapplyForm
	 * @param user
	 * @param loanapply
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public void eAloan(LoanapplyForm loanapplyForm, O2oLoanapplyEntity loanapply) {
		// 修改主表
		loanDao.updateLoanapply(loanapplyForm, userUtils);
		// 记录到操作日志表
		ObjectMapper mapper = new ObjectMapper();
		try {
			o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_ND,
					mapper.writeValueAsString(loanapply), mapper.writeValueAsString(loanapply));
		} catch (Exception e) {
			e.printStackTrace();
		}
		LoanapplyExpand loanapplyExpand = loanapplyExpandDao.queryLoanapplyNo(loanapplyForm.getLoanapplyNo());
		BigDecimal year = new BigDecimal(12);
		// 管理费=(贷款金额*年化费率)/12*贷款月数
		BigDecimal manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate())).divide(year, 2, BigDecimal.ROUND_HALF_UP);
		if (loanapplyExpand == null) {
			LoanapplyExpand expand = new LoanapplyExpand();
			expand.setPaymentType(loanapplyForm.getPaymentType());
			expand.setBankLoanName(loanapplyForm.getBankLoanName());
			expand.setGeneralRate(loanapplyForm.getGeneralRate());
			expand.setBillStatus(StatusContexts.BZJ_STATUS_NEW);
			expand.setBillCode(loanapply.getBillCode());
			expand.setRisk(loanapplyForm.getRisk());
			expand.setUpdator(userUtils.getUpdateOr());
			expand.setCreator(userUtils.getCreateOr());
			expand.setCreat_time(new Date());
			expand.setUpdateTime(new Date());
			expand.setDelFlag(StatusContexts.O2O_NO);
			expand.setRemark(loanapplyForm.getRemark());
			expand.setLoanapply_no(loanapplyForm.getLoanapplyNo());
			
			expand.setRecManger(manger);
			expand.setDepositrate(loanapplyForm.getDepositrate());
			expand.setManagefeerate(loanapplyForm.getManagefeerate());
			expand.setRecRisk(new BigDecimal(0));
			expand.setRecDeposite(new BigDecimal(0));
			expand.setReceiveDeposit(new BigDecimal(0));;
			expand.setRisk(loanapplyForm.getRisk());
			loanapplyExpandDao.insert(expand);
		} else {
			BigDecimal recRisk = new BigDecimal(0);
			loanapplyForm.setRisk(new BigDecimal(0));
			loanapplyExpandDao.updateLoanapplyExpand(manger, loanapply, loanapplyForm, recRisk, loanapplyExpand);
		}
		// 内审审批 历史记录
		AuditComments auditComments = new AuditComments();
		auditComments.setCreateDate(new Date());
		auditComments.setEmpLoyeNo(userUtils.getUser().getNo());
		auditComments.setRisk(loanapplyForm.getRisk());
		auditComments.setEmpLoyeName(userUtils.getUser().getCname());
		auditComments.setLoanapplyNo(loanapplyForm.getLoanapplyNo());
		auditComments.setLoanrate(loanapplyForm.getLoanrate());
		auditComments.setLoanterm(loanapplyForm.getLoanTerm());
		auditComments.setDepositrate(loanapplyForm.getDepositrate());
		auditComments.setRemark(loanapplyForm.getRemark());
		auditComments.setManagefeerate(loanapplyForm.getManagefeerate());
		auditComments.setCustomersalesamount(loanapply.getCustomerSalesamount());
		auditComments.setEacooperationdate(loanapply.getEaCooperationDate());
		auditComments.setEapurchaseamount(loanapply.getEaPurchaseamount());
		auditComments.setRepaymentway(loanapplyForm.getRepayMentway());
		auditComments.setBankLoanName(loanapplyForm.getBankLoanName());
		auditComments.setPaymentType(loanapplyForm.getPaymentType());
		auditComments.setGeneralRate(loanapplyForm.getGeneralRate());
		auditComments.setEaMount(loanapplyForm.getEaMount());
		auditCommentsDao.insert(auditComments);
	}

	/**
	 * 终端贷 内审表单
	 * 
	 * @param loanapplyForm
	 * @param user
	 * @param loanapply
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public void bKloan(LoanapplyForm loanapplyForm, O2oLoanapplyEntity loanapply) {
		if (StatusContexts.LOAN_TYPE_BK.equals(loanapply.getLoanType())) {
			// 放款利率
			if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_BC)) {
				loanapplyForm.setLoanrate(BankRate.BANK_BC_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CBC)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CBC_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_GACZ)) {
				loanapplyForm.setLoanrate(BankRate.BANK_GACZ_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CCBHN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CCBHN_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_QLB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_QLB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CIBJN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CIBJN_RATE);
			}else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_JCB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_JCB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_ZZB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_ZZB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SPDBGZ)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SPDBGZ_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SXB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SXB_RATE);
			}else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_ZLB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_ZLB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SPDBJN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SPDBJN_RATE);
			} else {
				loanapplyForm.setLoanrate(BankRate.BANK_OTH_RATE);
			}
		}
		// 修改主表
		loanDao.updateLoanapply(loanapplyForm, userUtils);
		// 记录到操作日志表
		ObjectMapper mapper = new ObjectMapper();
		try {
			o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_ND,
					mapper.writeValueAsString(loanapply), mapper.writeValueAsString(loanapply));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 收取保证金与管理费
		// 1.管理费=(贷款金额*年化费率)/12*贷款月数
		// 2.风险补偿金=(贷款金额*年化费率)/12*贷款月数
		// 3.保证金=贷款金额*费率
		LoanapplyExpand loanapplyExpand = loanapplyExpandDao.queryLoanapplyNo(loanapplyForm.getLoanapplyNo());
		BigDecimal year = new BigDecimal(12);
		if (loanapplyExpand == null) {
			LoanapplyExpand expand = new LoanapplyExpand();
			expand.setPaymentType(loanapplyForm.getPaymentType());
			expand.setBankLoanName(loanapplyForm.getBankLoanName());
			expand.setGeneralRate(loanapplyForm.getGeneralRate());
			expand.setBillStatus(StatusContexts.BZJ_STATUS_NEW);
			expand.setBillCode(loanapply.getBillCode());
			expand.setRisk(loanapplyForm.getRisk());
			expand.setUpdator(userUtils.getUpdateOr());
			expand.setCreator(userUtils.getCreateOr());
			expand.setCreat_time(new Date());
			expand.setUpdateTime(new Date());
			expand.setDelFlag(StatusContexts.O2O_NO);
			expand.setRemark(loanapplyForm.getRemark());
			expand.setLoanapply_no(loanapplyForm.getLoanapplyNo());
			// 保证金=贷款金额*费率
			expand.setRecDeposite((loanapplyForm.getEaMount()).multiply((loanapplyForm.getDepositrate())));
			// 管理费=(贷款金额*年化费率)/12*贷款月数
			BigDecimal loanTerm = new BigDecimal(loanapplyForm.getLoanTerm());
			BigDecimal term = new BigDecimal(6);
			BigDecimal term1 = new BigDecimal(12);
			BigDecimal manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate()));
			// 风险保证金 不足半年按半年收取，超过半年按一年收取；管理费 不足半年，按半年收取，半年以上，按实际收取
			if (loanTerm.compareTo(term) == -1) {
				expand.setRecManger((manger.multiply(term).divide(year, 2, BigDecimal.ROUND_HALF_UP)));
				// 风险补偿金=(贷款金额*年化费率)/12*贷款月数
				expand.setRecRisk(((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(term)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP)));
			} else if (loanTerm.compareTo(term) == 0) {
				expand.setRecManger((manger.multiply(loanTerm).divide(year, 2, BigDecimal.ROUND_HALF_UP)));
				expand.setRecRisk(((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(loanTerm)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP)));
			} else {
				expand.setRecManger((manger.multiply(loanTerm).divide(year, 2, BigDecimal.ROUND_HALF_UP)));
				expand.setRecRisk(((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(term1)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP)));
			}
			expand.setDepositrate(loanapplyForm.getDepositrate());
			expand.setManagefeerate(loanapplyForm.getManagefeerate());
			expand.setRisk(loanapplyForm.getRisk());
			loanapplyExpandDao.insert(expand);
		} else {
			// 管理费=(贷款金额*年化费率)/12*贷款月数
			BigDecimal loanTerm = new BigDecimal(loanapplyForm.getLoanTerm());
			BigDecimal term = new BigDecimal(6);
			BigDecimal term1 = new BigDecimal(12);
			BigDecimal manger = null;
			BigDecimal recRisk = null;
			// 风险保证金 不足半年按半年收取，超过半年按一年收取；管理费 不足半年，按半年收取，半年以上，按实际收取
			if (loanTerm.compareTo(term) == -1) {
				manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate())).multiply(term)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP);
				recRisk = ((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(term).divide(year, 2,
						BigDecimal.ROUND_HALF_UP));
			} else if (loanTerm.compareTo(term) == 0) {
				manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate())).multiply(loanTerm)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP);
				recRisk = ((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(loanTerm).divide(year, 2,
						BigDecimal.ROUND_HALF_UP));
			} else {
				manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate())).multiply(loanTerm)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP);
				recRisk = ((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(term1).divide(year, 2,
						BigDecimal.ROUND_HALF_UP));
			}
			loanapplyExpandDao.updateLoanapplyExpand(manger, loanapply, loanapplyForm, recRisk, loanapplyExpand);
		}
		// 内审审批 历史记录
		AuditComments auditComments = new AuditComments();
		auditComments.setCreateDate(new Date());
		auditComments.setEmpLoyeNo(userUtils.getUser().getNo());
		auditComments.setRisk(loanapplyForm.getRisk());
		auditComments.setEmpLoyeName(userUtils.getUser().getCname());
		auditComments.setLoanapplyNo(loanapplyForm.getLoanapplyNo());
		auditComments.setLoanrate(loanapplyForm.getLoanrate());
		auditComments.setLoanterm(loanapplyForm.getLoanTerm());
		auditComments.setDepositrate(loanapplyForm.getDepositrate());
		auditComments.setRemark(loanapplyForm.getRemark());
		auditComments.setManagefeerate(loanapplyForm.getManagefeerate());
		auditComments.setCustomersalesamount(loanapply.getCustomerSalesamount());
		auditComments.setEacooperationdate(loanapply.getEaCooperationDate());
		auditComments.setEapurchaseamount(loanapply.getEaPurchaseamount());
		auditComments.setRepaymentway(loanapplyForm.getRepayMentway());
		auditComments.setBankLoanName(loanapplyForm.getBankLoanName());
		auditComments.setPaymentType(loanapplyForm.getPaymentType());
		auditComments.setGeneralRate(loanapplyForm.getGeneralRate());
		auditComments.setEaMount(loanapplyForm.getEaMount());
		auditCommentsDao.insert(auditComments);
	}
	/**
	 * 终端贷 内审表单 _编辑内审
	 * 
	 * @param loanapplyForm
	 * @param user
	 * @param loanapply
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public void bKloan_ns(LoanapplyForm loanapplyForm, O2oLoanapplyEntity loanapply) {
		if (StatusContexts.LOAN_TYPE_BK.equals(loanapply.getLoanType())) {
			// 放款利率
			if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_BC)) {
				loanapplyForm.setLoanrate(BankRate.BANK_BC_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CBC)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CBC_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_GACZ)) {
				loanapplyForm.setLoanrate(BankRate.BANK_GACZ_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CCBHN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CCBHN_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_QLB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_QLB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CIBJN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CIBJN_RATE);
			}else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_JCB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_JCB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_ZZB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_ZZB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SPDBGZ)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SPDBGZ_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SXB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SXB_RATE);
			}else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_ZLB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_ZLB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SPDBJN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SPDBJN_RATE);
			} else {
				loanapplyForm.setLoanrate(BankRate.BANK_OTH_RATE);
			}
		}
		// 修改主表
		loanDao.updateLoanapply_ns(loanapplyForm, userUtils);
		// 记录到操作日志表
		ObjectMapper mapper = new ObjectMapper();
		try {
			o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_ND,
					mapper.writeValueAsString(loanapply), mapper.writeValueAsString(loanapply));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 收取保证金与管理费
		// 1.管理费=(贷款金额*年化费率)/12*贷款月数
		// 2.风险补偿金=(贷款金额*年化费率)/12*贷款月数
		// 3.保证金=贷款金额*费率
		LoanapplyExpand loanapplyExpand = loanapplyExpandDao.queryLoanapplyNo(loanapplyForm.getLoanapplyNo());
		BigDecimal year = new BigDecimal(12);
		if (loanapplyExpand == null) {
			LoanapplyExpand expand = new LoanapplyExpand();
			expand.setPaymentType(loanapplyForm.getPaymentType());
			expand.setBankLoanName(loanapplyForm.getBankLoanName());
			expand.setGeneralRate(loanapplyForm.getGeneralRate());
			expand.setBillStatus(StatusContexts.BZJ_STATUS_NEW);
			expand.setBillCode(loanapply.getBillCode());
			expand.setRisk(loanapplyForm.getRisk());
			expand.setUpdator(userUtils.getUpdateOr());
			expand.setCreator(userUtils.getCreateOr());
			expand.setCreat_time(new Date());
			expand.setUpdateTime(new Date());
			expand.setDelFlag(StatusContexts.O2O_NO);
			expand.setRemark(loanapplyForm.getRemark());
			expand.setLoanapply_no(loanapplyForm.getLoanapplyNo());
			// 保证金=贷款金额*费率
			expand.setRecDeposite((loanapplyForm.getEaMount()).multiply((loanapplyForm.getDepositrate())));
			// 管理费=(贷款金额*年化费率)/12*贷款月数
			BigDecimal loanTerm = new BigDecimal(loanapplyForm.getLoanTerm());
			BigDecimal term = new BigDecimal(6);
			BigDecimal term1 = new BigDecimal(12);
			BigDecimal manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate()));
			// 风险保证金 不足半年按半年收取，超过半年按一年收取；管理费 不足半年，按半年收取，半年以上，按实际收取
			if (loanTerm.compareTo(term) == -1) {
				expand.setRecManger((manger.multiply(term).divide(year, 2, BigDecimal.ROUND_HALF_UP)));
				// 风险补偿金=(贷款金额*年化费率)/12*贷款月数
				expand.setRecRisk(((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(term)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP)));
			} else if (loanTerm.compareTo(term) == 0) {
				expand.setRecManger((manger.multiply(loanTerm).divide(year, 2, BigDecimal.ROUND_HALF_UP)));
				expand.setRecRisk(((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(loanTerm)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP)));
			} else {
				expand.setRecManger((manger.multiply(loanTerm).divide(year, 2, BigDecimal.ROUND_HALF_UP)));
				expand.setRecRisk(((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(term1)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP)));
			}
			expand.setDepositrate(loanapplyForm.getDepositrate());
			expand.setManagefeerate(loanapplyForm.getManagefeerate());
			expand.setRisk(loanapplyForm.getRisk());
			loanapplyExpandDao.insert(expand);
		} else {
			// 管理费=(贷款金额*年化费率)/12*贷款月数
			BigDecimal loanTerm = new BigDecimal(loanapplyForm.getLoanTerm());
			BigDecimal term = new BigDecimal(6);
			BigDecimal term1 = new BigDecimal(12);
			BigDecimal manger = null;
			BigDecimal recRisk = null;
			// 风险保证金 不足半年按半年收取，超过半年按一年收取；管理费 不足半年，按半年收取，半年以上，按实际收取
			if (loanTerm.compareTo(term) == -1) {
				manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate())).multiply(term)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP);
				recRisk = ((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(term).divide(year, 2,
						BigDecimal.ROUND_HALF_UP));
			} else if (loanTerm.compareTo(term) == 0) {
				manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate())).multiply(loanTerm)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP);
				recRisk = ((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(loanTerm).divide(year, 2,
						BigDecimal.ROUND_HALF_UP));
			} else {
				manger = (loanapplyForm.getEaMount()).multiply((loanapplyForm.getManagefeerate())).multiply(loanTerm)
						.divide(year, 2, BigDecimal.ROUND_HALF_UP);
				recRisk = ((loanapplyForm.getEaMount()).multiply(loanapplyForm.getRisk()).multiply(term1).divide(year, 2,
						BigDecimal.ROUND_HALF_UP));
			}
			loanapplyExpandDao.updateLoanapplyExpand(manger, loanapply, loanapplyForm, recRisk, loanapplyExpand);
		}
		// 内审审批 历史记录
		AuditComments auditComments = new AuditComments();
		auditComments.setCreateDate(new Date());
		auditComments.setEmpLoyeNo(userUtils.getUser().getNo());
		auditComments.setRisk(loanapplyForm.getRisk());
		auditComments.setEmpLoyeName(userUtils.getUser().getCname());
		auditComments.setLoanapplyNo(loanapplyForm.getLoanapplyNo());
		auditComments.setLoanrate(loanapplyForm.getLoanrate());
		auditComments.setLoanterm(loanapplyForm.getLoanTerm());
		auditComments.setDepositrate(loanapplyForm.getDepositrate());
		auditComments.setRemark(loanapplyForm.getRemark());
		auditComments.setManagefeerate(loanapplyForm.getManagefeerate());
		auditComments.setCustomersalesamount(loanapply.getCustomerSalesamount());
		auditComments.setEacooperationdate(loanapply.getEaCooperationDate());
		auditComments.setEapurchaseamount(loanapply.getEaPurchaseamount());
		auditComments.setRepaymentway(loanapplyForm.getRepayMentway());
		auditComments.setBankLoanName(loanapplyForm.getBankLoanName());
		auditComments.setPaymentType(loanapplyForm.getPaymentType());
		auditComments.setGeneralRate(loanapplyForm.getGeneralRate());
		auditComments.setEaMount(loanapplyForm.getEaMount());
		auditCommentsDao.insert(auditComments);
	}
	
	public String checkNS(O2oLoanUserEntity  loanUserEntity){
		if (loanUserEntity == null) {
			return  "借款人信息未完善";
		}
		CustomerBasicInfo expand = o2oLoanapplyService.getCustomerEntityById(loanUserEntity.getId());//查询借款人扩展信息
		if (expand == null) {
			return  "借款人信息未完善";
		}
		boolean familyName = StringUtil.isEmpty(loanUserEntity.getUserSurName());
		boolean givenName = StringUtil.isEmpty(loanUserEntity.getUserName());
		boolean namePinyin = StringUtil.isEmpty(loanUserEntity.getUserNamePinyin());
		if (familyName) {
			return  "借款人姓不能为空，请编辑借款人信息";
		}
		if (givenName) {
			return  "借款人名不能为空，请编辑借款人信息";
		}
		if (namePinyin) {
			return  "借款人姓名拼音不能为空，请编辑借款人信息";
		}
		
//		// 性别由身份证号算出
//		if (StringUtil.isEmpty(loanUserEntity.getSex())) {
//			return  "借款人性别不能为空，请编辑借款人信息";
//		}
		
		if (StringUtils.isBlank(expand.getHomePhone())){
			return  "借款人住宅电话不能为空，请编辑借款人信息";
		}
		
		if (StringUtils.isBlank(expand.getEducation())){
			return  "借款人学历不能为空，请编辑借款人信息";
		}
		
//		if (0 == expand.getMaritalStatus()){
//			return  "婚姻情况不能为空，请编辑借款人信息";
//		}
		if (StringUtils.isBlank(expand.getChildrenInfo())){
			return  "子女情况不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getIssuingAuthority())) {
			return  "发证机构不能为空，请编辑借款人信息";
		}
		if (null == expand.getLicenseExpirationDate()) {
			return  "证件日期不能为空，请编辑借款人信息";
		}
		
		if (StringUtils.isBlank(expand.getWechat())){
			return  "微信号不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getPostcode())) {
			return  "单位邮编不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getRecipientProvince())) {
			return  "收件地址（省）不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getRecipientCity())) {
			return  "收件地址（市）不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getRecipientAddress())) {
			return  "收件地址详细不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getAccountProvince())) {
			return  "户口所在省不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getAccountCity())) {
			return  "户口所在市不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getPermanentresidence())) {
			return  "户口所在详细地不能为空，请编辑借款人信息";
		}
		if (0 == expand.getLiveYears()) {
			return  "居住年限地不能为空，请编辑借款人信息";
		}
		return StatusContexts.SUCCESS;
		
	}
	
	public String checkSpouseNS(O2oLoanUserEntity  loanUserEntity){
		if (loanUserEntity == null) {
			return  "借款人信息未完善";
		}
		CustomerBasicInfo expand = o2oLoanapplyService.getCustomerEntityById(loanUserEntity.getId());//查询借款人扩展信息
		if (expand == null) {
			return  "借款人信息未完善";
		}
		boolean familyName = StringUtil.isEmpty(loanUserEntity.getUserSurName());
		boolean givenName = StringUtil.isEmpty(loanUserEntity.getUserName());
		if (familyName) {
			return  "配偶姓不能为空，请编辑借款人信息";
		}
		if (givenName) {
			return  "配偶名不能为空，请编辑借款人信息";
		}
		if (StringUtil.isEmpty(loanUserEntity.getSex())) {
			return  "配偶性别不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getIssuingAuthority())) {
			return  "配偶发证机构不能为空，请编辑借款人信息";
		}
		if (expand.getLicenseExpirationDate() == null) {
			return  "配偶证件日期不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getWechat())){
			return  "配偶微信号不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getEducation())){
			return  "配偶学历不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getAccountProvince())) {
			return  "配偶户口所在省不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getAccountCity())) {
			return  "配偶户口所在市不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getPermanentresidence())) {
			return  "配偶户口所在详细地不能为空，请编辑借款人信息";
		}
		if (StringUtils.isBlank(expand.getWorkUnit())) {
			return  "配偶工作单位不能为空，请编辑借款人信息";
		}
		return StatusContexts.SUCCESS;
		
	}
	
	public String checkNSapply(O2oLoanapplyEntity loan ){
		if (StringUtil.isEmpty(loan.getGuarAnteeWay())) { //检查还款方式
			return  "担保方式不能为空，请编辑贷款信息";
		}
		if (StringUtils.isBlank(loan.getRepayMentway())) {
			return  "还款方式不能为空，请编辑贷款信息";
		}
		if (StatusContexts.LOAN_TYPE_BP.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_BP_JX.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_SG.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_YC.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_SC.equals(loan.getLoanType())) {
			if (StringUtils.isBlank(loan.getPartnerId())){
				return  "请填写合作方";
			}
		}
		if (StringUtils.isBlank(loan.getReferrerName())){
			return  "推荐人不能为空，请编辑借款人信息";
		}
		if (loan.getLoanTerm() == 0){
			return  "贷款期限不能为空，请编辑借款人信息";
		}
		return StatusContexts.SUCCESS;
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               check贷款信息
	 *               </p>
	 * @author CXW
	 * @date 2017年7月10日 下午3:39:23
	 * @version V1.0
	 */
	public  String checkLoanApply(O2oLoanapplyEntity loan) {
		String result = "SUCCESS";
		if(StringUtil.isBlank(loan.getLoanType()) ){
			return "贷款类型不能为空，请编辑贷款信息";
		}
		if(StringUtil.isBlank(loan.getLtd()) ){
			return "经办平台不能为空，请编辑贷款信息";
		}
		if(StringUtil.isBlank(loan.getOperatorNo()) ){
			return "信贷经理不能为空，请编辑贷款信息";
		}
		if(StringUtil.isBlank(loan.getOperationModel()) ){
			return "经营模式不能为空，请编辑贷款信息";
		}
		if(StatusContexts.LOAN_TYPE_BK.equals(loan.getLoanType()) && StringUtil.isBlank(loan.getCustomerNo())){
			return "SD客户名称不能为空，请编辑贷款信息";
		}
		if((StatusContexts.LOAN_TYPE_BP.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_BP_JX.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_SG.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_YC.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_SC.equals(loan.getLoanType())) && StringUtil.isBlank(loan.getPartnerId())){
			return "渠道名称不能为空，请编辑贷款信息";
		}
	
		if(null == loan.getLoanaMount()){
			return "申请金额不能为空，请编辑贷款信息";
		}
		return result;
	}
	
	@Autowired
	O2oLoanGsService gsService;
	@Autowired
	O2oLoanGsMainProductService pgsService;
	@Autowired
	O2oLoanScService scService;
	/**
	 * @Description:
	 *               <p>
	 *               提交内审check蔬果贷和商超贷表单是否保存
	 *               </p>
	 * @author CXW
	 * @date 2017年10月17日 下午1:42:09
	 * @version V1.0
	 */
	public String checkNsSG(O2oLoanapplyEntity loanEntity) {
		if (StatusContexts.LOAN_TYPE_SG.equals(loanEntity.getLoanType())) {
			O2oLoanGsInfo gsInfo = gsService.getLoanapplyNo(loanEntity.getLoanapplyNo());
			if (null == gsInfo) {
				return "经营信息不能为空，请编辑经营信息！";
			}
			O2oLoanGsMainproductInfo gsMainproductInfo = pgsService.getEntityByLoan(loanEntity.getLoanapplyNo());
			if (null == gsMainproductInfo) {
				return "经营补充信息主要产品销售情况不能为空，请新增！";
			}
		}
		if (StatusContexts.LOAN_TYPE_SC.equals(loanEntity.getLoanType())) {
			O2oLoanScInfo gsInfo = scService.getLoanapplyNo(loanEntity.getLoanapplyNo());
			if (null == gsInfo) {
				return "经营信息不能为空，请编辑经营信息！";
			}
		}
		return StatusContexts.SUCCESS;
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               check表单是否填写
	 *               </p>
	 * @author CXW
	 * @date 2017年8月16日 上午10:01:38
	 * @version V1.0
	 */
	public String checkNsBd(O2oLoanapplyEntity loanEntity){
		logger.info("Check内审动态表单:[{}]", "nsEditDetail/ns_ptxdjl");
		if (!StringUtil.isNotBlank(String.valueOf(loanEntity.getLoanTerm()))) {
			return "货款期限不能空，请编辑内审信息";
		}
		if (!StringUtil.isNotBlank(loanEntity.getRepayMentway())) {
			return "还款方式不能空，请编辑内审信息";
		}
		if (loanEntity.getLoanrate() == null) {
			return "贷款利率不能空，请编辑内审信息";
		}
		if (loanEntity.getManagefeerate() == null) {
			return "管理费率不能空，请编辑内审信息";
		}
		if (loanEntity.getDepositrate() == null) {
			return "保证金费率不能空，请编辑内审信息";
		}
		LoanapplyExpand loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(loanEntity.getLoanapplyNo());
		if (loanapplyExpand == null) {
			return "内审审批意见表单信息未保存，请编辑内审信息";
		}
		if (loanapplyExpand.getRisk() == null) {
			return "保证金费率不能空，请编辑内审信息";
		}
		if (loanEntity.getEaMount() == null) {
			return "ea批复额度不能为空，请编辑内审信息";
		}
		return StatusContexts.SUCCESS;
	}
	
	
	/**
	 * @Description:
	 *               <p>
	 *               提交内审check经营补充信息 
	 *               </p>
	 * @author yy
	 * @date 2017年10月17日 下午1:42:09
	 * @version V1.0
	 */
	public ModelResult<Boolean> checkJYBCXX(O2oLoanapplyEntity loan) {
		ModelResult<Boolean> modelResult = new ModelResult<Boolean>().withModel(Boolean.TRUE);//默认是成功
		if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_SG)){
			O2oLoanGsInfo gsInfo = gsService.getLoanapplyNo(loan.getLoanapplyNo());
			
			if(gsInfo==null){
				return modelResult.withModel(false).withError("NSCHECK_014", "渠道数据不能为空");
			}
			//渠道数据
			if (gsInfo.getStartOperateTime()==null) {
				return modelResult.withModel(false).withError("NSCHECK_014_01", "渠道数据本市场经营开始时间不能为空");
			}
			if (null == gsInfo.getIsParking()) {
				return modelResult.withModel(false).withError("NSCHECK_014_02", "渠道数据档口有无车位不能为空");
			}
			//上游信息
			if (null == gsInfo.getIsOwnFarm()) {
				return modelResult.withModel(false).withError("NSCHECK_014_03", "上游信息是否有自有农场不能为空");
			}
			
			if (null == gsInfo.getIsOwnFarm()) {
				return modelResult.withModel(false).withError("NSCHECK_014_04", "上游信息是否有自有农场不能为空");
			}
			
			if (null == gsInfo.getIsFarmer()) {
				return modelResult.withModel(false).withError("NSCHECK_014_05", "上游信息是否向固定农户采购不能为空");
			}
			
			if (null == gsInfo.getIsOwnFarm()) {
				return modelResult.withModel(false).withError("NSCHECK_014_02", "上游信息是否向其他供菜商采购不能为空");
			}
			if (null == gsInfo.getIsOtherPurchase()) {
				return modelResult.withModel(false).withError("NSCHECK_014_02", "上游信息是否有自有农场不能为空");
			}
//			if (null == gsInfo.getOfficeprovince()) {
//				return modelResult.withModel(false).withError("NSCHECK_014_02", "上游信息自有农场地址：不能为空");
//			}
			if (null == gsInfo.getOtherModeRemark()) {
				return modelResult.withModel(false).withError("NSCHECK_014_02", "上游信息其他方式说明不能为空");
			}
			
			//下游信息
			if (null == gsInfo.getTwoBatch()) {
				return modelResult.withModel(false).withError("NSCHECK_014_02", "下游信息二批商近六个月销售量不能为空");
			}
			if (null == gsInfo.getSupermarket()) {
				return modelResult.withModel(false).withError("NSCHECK_014_02", "下游信息商超近六个月销售量不能为空");
			}
			if (null == gsInfo.getGroupPurch()) {
				return modelResult.withModel(false).withError("NSCHECK_014_02", "下游信息团购（酒店、食堂等）近六个月销售量不能为空");
			}
			if (null == gsInfo.getRetail()) {
				return modelResult.withModel(false).withError("NSCHECK_014_02", "下游信息零售终端近六个月销售量不能为空");
			}
			//主要产品销售情况 /gs_info_plist
			int bkpcount = productService.queryEntitysSize(loan.getLoanapplyNo());
			if (bkpcount<1) {
				return modelResult.withModel(false).withError("NSCHECK_016_04", "主要销售产品不能为空");
			}
		}else if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_SC)){//loanType=='SC' /rmongo/sc_info_lno
			O2oLoanScInfo gsInfosc = scService.getLoanapplyNo(loan.getLoanapplyNo());
			
			if(gsInfosc==null){
				return modelResult.withModel(false).withError("NSCHECK_015", "渠道数据不能为空");
			}
			//渠道数据
			if (gsInfosc.getWhitelistTime()==null) {
				return modelResult.withModel(false).withError("NSCHECK_015_01", "与白名单内商超合作开始时间");
			}
			if (gsInfosc.getTwoBatch()==null) {
				return modelResult.withModel(false).withError("NSCHECK_015_02", "二批商近六个月销售量不能为空");
			}
			
			if (gsInfosc.getSupermarket()==null) {
				return modelResult.withModel(false).withError("NSCHECK_015_03", "商超近六个月销售量不能为空");
			}
			if (gsInfosc.getDirectRetail()==null) {
				return modelResult.withModel(false).withError("NSCHECK_015_04", "直接零售近六个月销售量不能为空");
			}
			if (gsInfosc.getRetail()==null) {
				return modelResult.withModel(false).withError("NSCHECK_015_05", "零售终端近六个月销售量不能为空");
			}
			//十大下游客户近6月供货量
			 int xycS = cService.queryEntitysSize(loan.getLoanapplyNo());
			 if (xycS<1) {
					return modelResult.withModel(false).withError("NSCHECK_015_06", "十大下游客户近6月供货量必须有一条");
			}
			//十大销售产品
			int tenS = tenSService.queryEntitysSize(loan.getLoanapplyNo());
			if (tenS<1) {
				return modelResult.withModel(false).withError("NSCHECK_015_07", "十大销售产品必须有一条");
			}
			
			
		}else if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BP)||
				loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BP_JX)||
				loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)
				){// /bk_info_view
			O2oLoanBkInfo bkInfo = o2oLoanBkService.getEntity(loan.getLoanapplyNo());
			if(bkInfo==null){
				return modelResult.withModel(false).withError("NSCHECK_016", "渠道数据不能为空");
			}
			//渠道数据
			if (bkInfo.getProductName()==null) {
				return modelResult.withModel(false).withError("NSCHECK_016_01", "与渠道企业采购的产品不能为空");
			}
			if (bkInfo.getMonthPrice()==null) {
				return modelResult.withModel(false).withError("NSCHECK_016_02", "月均合作额（以近6个月金额为标准）不能为空");
			}
			if (bkInfo.getStartCoopDate()==null) {// 对终端贷、流通贷——厂家、流通贷——经销商三种类型提交内审时校验该字段"与渠道企业合作起始时间"
				return modelResult.withModel(false).withError("NSCHECK_016_05", "与渠道企业合作起始时间不能为空");
			}
			//上游信息
			int yscount = o2oLoanBksyService.queryEntitysSize(loan.getLoanapplyNo());
			if (yscount<1) {
				return modelResult.withModel(false).withError("NSCHECK_016_03", "上游信息必有一条");
			}
			
			//主要销售产品
			int bkpcount = o2oLoanBkpService.queryEntitysSize(loan.getLoanapplyNo());
			if (bkpcount<1) {
				return modelResult.withModel(false).withError("NSCHECK_016_04", "主要销售产品必有一条");
			}
			
		}
		return modelResult;
	}
	
	
}
